package com.lanqiao.controller;

import com.lanqiao.dao.userDAO;
import com.lanqiao.entity.userinfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class indexController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if(req.getSession().getAttribute("user_ID")==null){
            //获取cookie的信息
            Cookie[] cookies = req.getCookies();
            String user_ID = null;
            if(cookies!=null){
                for(Cookie cookie : cookies){
                    if("user_ID".equals(cookie.getName())){
                        user_ID = cookie.getValue();
                    }
                }
            }

            if(user_ID==null){
                resp.getWriter().println(
                        "<script>location.href='user?method=tologin'</script>"
                );
            }else {
                userDAO userDAO = new userDAO();
                List<userinfo> userinfoList = userDAO.selectById(user_ID);
                req.getSession().setAttribute("user",userinfoList.get(0));
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }
        }else {
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }
}
